<template>
  <div>
      <div class="time">倒计时：{{date}}{{dateLibs}}</div>
      <div style="position:relative">
      <div v-for="item in tableData" :key="item.id">
        <el-row >
            <el-col :span="24">
                <div class="grid-content bg-purple">{{item.questionNumber}}.  {{item.title}}</div>
            </el-col>
        </el-row>
        <el-row style="margin-left:20px">
            <el-col :span="24">
                <el-radio v-if="item.optionA" style="margin-top:10px" v-model="item.answer" label="A">A.{{item.optionA}}</el-radio><br />
                <el-radio v-if="item.optionB" style="margin-top:10px" v-model="item.answer" label="B">B.{{item.optionB}}</el-radio><br />
                <el-radio v-if="item.optionC" style="margin-top:10px" v-model="item.answer" label="C">C.{{item.optionC}}</el-radio><br />
                <el-radio v-if="item.optionD" style="margin-top:10px" v-model="item.answer" label="D">D.{{item.optionD}}</el-radio><br />
                <el-radio v-if="item.optionE" style="margin-top:10px" v-model="item.answer" label="E">E.{{item.optionE}}</el-radio><br />
                <el-radio v-if="item.optionF" style="margin-top:10px" v-model="item.answer" label="F">F.{{item.optionF}}</el-radio>

            </el-col>
        </el-row>
      </div>
       <el-popconfirm
            title="确定提交试卷吗？"
            @confirm="submit"
            >
            <el-button slot="reference" class="submit" type="success" plain >提交</el-button>
            </el-popconfirm>
      </div>
  </div>
</template>

<script>
import webservice from "../../../api/webservice";
export default {
  data() {
    return {
      tableData: [],
      // 默认显示第几页
      currentPage: 1,
      // 个数选择器（可修改）
      pageSizes: [10, 20, 30, 40, 50],
      // 默认每页显示的条数（可修改）
      PageSize: 10,
      answerContent:[],//提交的试卷内容
      userID:'',
      date:'',
      leaveTime: '',
      dateLibs:'',
      submited:false,//是否已经提交
      examStartDate:'',//开始答题时间
      examEndDate:'',//答题结束时间
      scoreReault:{},//成绩结果
    };
  },
  created() {
    this.date = this.$route.params.time
    this.leaveTime = this.date*60*1000
  },
  mounted() {
    this.openTibs()
    this.userID = JSON.parse(sessionStorage.getItem('userInfo')).id
  },
  methods: {
    // 分页
    // 每页显示的条数
    handleSizeChange(val) {
      // 改变每页显示的条数
      this.PageSize = val;
      // 注意：在改变每页显示的条数时，要将页码显示到第一页
      this.currentPage = 1;
    },
    // 显示第几页
    handleCurrentChange(val) {
      // 改变默认的页数
      this.currentPage = val;
    },
    openTibs() {
        this.$confirm('请确认是否正式开始答题？一旦开始答题后请提交试卷后再离开此页面，否则将自动结束答题！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.getData();
        }).catch(() => {
          this.$router.push('/testList')  
        });
      },
    //计时器
    countTime(){
    this.leaveTime = this.leaveTime  - 1000;
    //定义变量 d,h,m,s保存倒计时的时间
    if (this.leaveTime >= 0) {
        var h = Math.floor(this.leaveTime / 1000 / 60 / 60 % 24);
        var m = Math.floor(this.leaveTime / 1000 / 60 % 60);
        var s = Math.floor(this.leaveTime / 1000 % 60);
        //递归每秒调用countTime方法，显示动态时间效果
        this.date = h + ':' + m + ':' + s 
        setTimeout(this.countTime, 1000);
    }else{
      this.dateLibs = '答题时间已结束'
      if(!this.submited){
        this.submit()
      }
    }
    },
    getData() {
      let _param = {
        paperId: this.$route.params.id,
      };
      let _params = JSON.stringify(_param);
      webservice.HttpPost("/api/questionStore/selectQuestionList", _params, (data) => {
        if (data.code === 200) {
          this.tableData = data.data;
          setTimeout(() => {
          this.countTime()
          let date = new Date();
          this.examStartDate =date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
          console.log(this.examStartDate)
          }, 1000);
        } else {
          this.$message.error({
            message: data.message,
            showClose: true,
            duration: 1000,
          });
          this.$router.push('/testList')
        }
      });
    },
    submit(){
      this.submited = true
        for(var i=0;i<this.tableData.length;i++){
            var answers = {}
            answers.questionId = this.tableData[i].id
            answers.answer = this.tableData[i].answer
            answers.studentId = this.userID
            this.answerContent.push(answers)
        }
        let date = new Date();
        this.examEndDate =date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
      let _param = {
        studentId:this.userID,
        paperId:this.$route.params.id,
        examStartDate:this.examStartDate,
        examEndDate:this.examEndDate,
        answerRecordList:this.answerContent
      }
      let _params = JSON.stringify(_param);
      webservice.HttpPost("/api/score/insertScore", _params, (data) => {
        this.answerContent = []
        if (data.code === 200) {
          this.scoreReault = data.data
          this.open()
        } else {
          this.$message.error({
            message: data.message,
            showClose: true,
            duration: 1000,
          });
        }
      });
    },
    open() {
        this.$alert(`您的成绩为：${this.scoreReault.score}`, '答题结束', {
          confirmButtonText: '确定',
          callback: action => {
            this.$router.push('/testList')
          }
        });
      },
  },
};
</script>

<style>
.submit{
    position:fixed;
    bottom: 10px;
    right: 10px;
    width: 80px;
    font-size: 16px;
}
.time{
  position: fixed;
  top: 110px;
  right: 10px;
}
</style>